//
//  WYHBLEPrinterTool.m
//  BluetoothPrint
//
//  Created by wang on 2017/11/3.
//  Copyright © 2017年 wang. All rights reserved.
//

#import "WYHBLEPrinterTool.h"
#import <CoreBluetooth/CoreBluetooth.h>

@interface WYHBLEPrinterTool()<CBCentralManagerDelegate, CBPeripheralDelegate>
@property (nonatomic, strong) CBCentralManager *centralManager;
@property (nonatomic, strong) CBPeripheral *peripheral;

@property (nonatomic, strong) CBCharacteristic *charactersticStr;//打印字符串的特征

@property (nonatomic, assign) BOOL isPrint;
@end



@implementation WYHBLEPrinterTool

/**
 开始打印 连接打印机
 */
- (void)startToPrint
{
    if (self.dataTool.printerParam.printerUUID.length == 0 ) {

        if ([_delegate respondsToSelector:@selector(printerErrorHint:)]) {
            [_delegate printerErrorHint:PrintErrorTypeSelectDevice];
        }
        return;
    }
    
    [self centralManager];
    self.isPrint = YES;
}

/**
 开始打印数据
 */
- (void)printData
{
    if (self.isPrint == NO) {
        return;
    }
    self.isPrint = NO;
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        //开始拼接数据
        [self.dataTool printAppendData];
        for (int i = 0; i < self.pageNum; i++) {
            for (int j = 0; j<self.dataTool.datas.count; j++) {
                NSData *data = self.dataTool.datas[j];
                [NSThread sleepForTimeInterval:self.dataTool.printerParam.sleepTime];
                // 需要注意的是特征的属性是否支持写数据
                [self.peripheral writeValue:data forCharacteristic:self.charactersticStr type:CBCharacteristicWriteWithResponse];
            }
            
//            for (NSData *data in self.dataTool.datas) {
//
//            }
            [NSThread sleepForTimeInterval:1];
        }
        [self.dataTool.datas removeAllObjects];
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([_delegate respondsToSelector:@selector(printerErrorHint:)]) {
                [_delegate printSuccess];
            }
        });
    });
}

//只要中心管理者初始化 就会触发此代理方法 判断手机蓝牙状态
- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    switch (central.state) {
        case 0:
            NSLog(@"CBCentralManagerStateUnknown");
            break;
        case 1:
            NSLog(@"CBCentralManagerStateResetting");
            break;
        case 2:
            NSLog(@"CBCentralManagerStateUnsupported");//不支持蓝牙
            break;
        case 3:
            NSLog(@"CBCentralManagerStateUnauthorized");
            break;
        case 4:
        {
//            NSLog(@"CBCentralManagerStatePoweredOff");//蓝牙未开启
            //请打开蓝牙
            if ([_delegate respondsToSelector:@selector(printerErrorHint:)]) {
                [_delegate printerErrorHint:PrintErrorTypeOff];
            }
        }
            break;
        case 5:
        {
//            NSLog(@"CBCentralManagerStatePoweredOn");//蓝牙已开启
            // 在中心管理者成功开启后再进行一些操作
            // 搜索外设
            [self.centralManager scanForPeripheralsWithServices:nil // 通过某些服务筛选外设
                                              options:nil]; // dict,条件
        }
            break;
        default:
            break;
    }
}

// 发现外设后调用的方法
- (void)centralManager:(CBCentralManager *)central // 中心管理者
 didDiscoverPeripheral:(CBPeripheral *)peripheral // 外设
     advertisementData:(NSDictionary *)advertisementData // 外设携带的数据
                  RSSI:(NSNumber *)RSSI // 外设发出的蓝牙信号强度
{
    if ([self.dataTool.printerParam.printerUUID isEqualToString:peripheral.identifier.UUIDString]) {
        self.peripheral = peripheral;
        
        [central connectPeripheral:peripheral options:nil];
        
    }
}
// 中心管理者连接外设成功
- (void)centralManager:(CBCentralManager *)central // 中心管理者
  didConnectPeripheral:(CBPeripheral *)peripheral // 外设
{
    NSLog(@"%s, line = %d, %@=连接成功", __FUNCTION__, __LINE__, peripheral.name);
    // 连接成功之后,可以进行服务和特征的发现
    // 外设发现服务,传nil代表不过滤
    // 这里会触发外设的代理方法 - (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
    //  设置外设的代理
    self.peripheral.delegate = self;
    [self.peripheral discoverServices:nil];
    [self.centralManager stopScan];
}

// 外设连接失败
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    NSLog(@"%s, line = %d, %@=连接失败", __FUNCTION__, __LINE__, peripheral.name);
}

// 丢失连接
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    NSLog(@"%s, line = %d, %@=断开连接", __FUNCTION__, __LINE__, peripheral.name);
}
// 这里会触发外设的代理方法
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
    for (CBService *service in peripheral.services) {
        [peripheral discoverCharacteristics:nil forService:service];
    }
}
// 发现外设服务里的特征的时候调用的代理方法(这个是比较重要的方法，你在这里可以通过事先知道UUID找到你需要的特征，订阅特征，或者这里写入数据给特征也可以)
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
    NSLog(@"%s, line = %d", __FUNCTION__, __LINE__);
    
    for (CBCharacteristic *character in service.characteristics) {
        //NSLog(@"%s, line = %d, char = %@", __FUNCTION__, __LINE__, cha);
        if ([self checkCharacter:character]) {
            self.charactersticStr = character;
            [self printData];
            break;
        }
    }
}

//从外围设备读数据
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
    NSLog(@"%@",error.userInfo);
}
- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    
}

/**
 判断是否可以打印

 */
- (BOOL)checkCharacter:(CBCharacteristic *)character
{
    NSString *str = [self getPropertiesString:character.properties];
    
    
    if (self.dataTool.printerParam.characteristicPropertyArr.count == 0) {
        if ([self str:str contains:@"Write"] && [self str:str contains:@"Read"] && [self str:str contains:@"Notify"] && [self str:str contains:@"Indicate"]) {
            return YES;
        }
    }else{
        BOOL isPrint = YES;
        for (NSString *string in self.dataTool.printerParam.characteristicPropertyArr) {
            if([self str:str contains:string] == NO){
                isPrint = NO;
            }
        }
        if (isPrint) {
            return YES;
        }
    }
    
    if ([self str:str contains:@"WriteWithoutResponse"]) {
        //芝柯 ds1900得实 210针式打印机
        return YES;
    }

    return NO;
}
-(BOOL)str:(NSString *)str contains:(NSString *)string
{
    if(str == nil){
        str = @"";
    }
    if(string.length == 0){
        return NO;
    }
    return [str rangeOfString:string].length;
}
/**
 *  拼接特征值
 *
 *  @param properties 单个属性
 *
 *  @return 拼接后的属性
 */
- (NSString *)getPropertiesString:(CBCharacteristicProperties)properties{
    NSMutableString *s = [[NSMutableString alloc]init];
    [s appendString:@""];
    
    if ((properties & CBCharacteristicPropertyBroadcast) == CBCharacteristicPropertyBroadcast) {
        [s appendString:@" Broadcast"];
    }
    if ((properties & CBCharacteristicPropertyRead) == CBCharacteristicPropertyRead) {
        [s appendString:@" Read"];
    }
    if ((properties & CBCharacteristicPropertyWriteWithoutResponse) == CBCharacteristicPropertyWriteWithoutResponse) {
        [s appendString:@" WriteWithoutResponse"];
    }
    if ((properties & CBCharacteristicPropertyWrite) == CBCharacteristicPropertyWrite) {
        [s appendString:@" Write"];
    }
    if ((properties & CBCharacteristicPropertyNotify) == CBCharacteristicPropertyNotify) {
        [s appendString:@" Notify"];
    }
    if ((properties & CBCharacteristicPropertyIndicate) == CBCharacteristicPropertyIndicate) {
        [s appendString:@" Indicate"];
    }
    if ((properties & CBCharacteristicPropertyAuthenticatedSignedWrites) == CBCharacteristicPropertyAuthenticatedSignedWrites) {
        [s appendString:@" AuthenticatedSignedWrites"];
    }
    if ((properties & CBCharacteristicPropertyExtendedProperties) == CBCharacteristicPropertyExtendedProperties) {
        [s appendString:@" ExtendedProperties"];
    }
    if ((properties & CBCharacteristicPropertyNotifyEncryptionRequired) == CBCharacteristicPropertyNotifyEncryptionRequired) {
        [s appendString:@" NotifyEncryptionRequired"];
    }
    if ((properties & CBCharacteristicPropertyIndicateEncryptionRequired) == CBCharacteristicPropertyIndicateEncryptionRequired) {
        [s appendString:@" IndicateEncryptionRequired"];
    }
    
    if ([s length]<2) {
        [s appendString:@"unknow"];
    }
    return s;
}
- (NSInteger)pageNum
{
    if (_pageNum) {
        return _pageNum;
    }
    return 1;
}
- (CBCentralManager *)centralManager
{
    if (_centralManager == nil) {
        _centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
    }
    return _centralManager;
}
@end
